﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;

namespace RemoteSpark
{
    class SparkIo
    {
        static string deviceId = "55ff73065075555308331487";
        static string authorization = "ccda76dbe043b0a5db08be2ca7626ae442668f7e";
        static string url = string.Format("https://api.spark.io/v1/devices/{0}/led", deviceId);

        //internal async static Task<Response> Set(string p1, string p2)
        //{
        //    Response resp = new Response();
       
        //    WebRequest request = WebRequest.Create(url);
        //    request.Headers["Authorization"] = string.Format("Bearer {0}", authorization);
        //    request.Method = "POST";
        //    string postData = string.Format("params={0},{1}", p1,p2);
        //    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        //    request.ContentType = "application/x-www-form-urlencoded";
        //    request.ContentLength = byteArray.Length;
        //    Stream dataStream = await request.GetRequestStreamAsync();
        //    dataStream.Write(byteArray, 0, byteArray.Length);
        //    dataStream.Close();
        //    WebResponse webResponse = await request.GetResponseAsync(new TimeSpan(0,0,5000));
        //    // Display the status.
        //    resp.Result = ((HttpWebResponse)webResponse).StatusCode == HttpStatusCode.OK;
        //    // Get the stream containing content returned by the server.
        //    dataStream = webResponse.GetResponseStream();
        //    // Open the stream using a StreamReader for easy access.
        //    StreamReader reader = new StreamReader(dataStream);
        //    // Read the content.
        //    resp.Description = reader.ReadToEnd();
        //    // Display the content.
        //    reader.Close();
        //    dataStream.Close();
        //    webResponse.Close();
            
        //    return resp;
        //}
        internal async static Task<LedResponse> Set(string p1, string p2)
        {
            Windows.Web.Http.HttpClient request = new Windows.Web.Http.HttpClient();

            string postData = string.Format("params={0},{1}", p1, p2);
            HttpRequestMessage mSent = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
            mSent.Content = new HttpStringContent(postData, Windows.Storage.Streams.UnicodeEncoding.Utf8);
            mSent.Headers["Authorization"] = string.Format("Bearer {0}", authorization);

            HttpResponseMessage mReceived = await request.SendRequestAsync(mSent, HttpCompletionOption.ResponseContentRead);
            string json = string.Empty;
            if (mReceived.IsSuccessStatusCode)
            {
                json = await mReceived.Content.ReadAsStringAsync();
            }

            var resp = JsonConvert.DeserializeObject<LedResponse>(json);
            resp.PlainJson = json;
            return resp;
        }

        internal async static Task<TemperatureResponse> GetTemperature()
          {
            string json;
            WebRequest request = WebRequest.Create(string.Format("https://api.spark.io/v1/devices/{0}/temperature", deviceId));
            request.Headers["Authorization"] = string.Format("Bearer {0}", authorization);
            request.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString();
            request.Method = "GET";
            using (WebResponse webResponse = await request.GetResponseAsync(new TimeSpan(0, 0, 5000)))
            {
                using (var dataStream = webResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }
            var resp = JsonConvert.DeserializeObject<TemperatureResponse>(json);
            return resp;
        }
    }
    //internal static class WebRequestExtensions
    //{
    //    internal static Task<WebResponse> GetResponseAsync(this WebRequest request, TimeSpan timeout)
    //    {
    //        return Task.Factory.StartNew<WebResponse>(() =>
    //        {
    //            var t = Task.Factory.FromAsync<WebResponse>(
    //                request.BeginGetResponse,
    //                request.EndGetResponse,
    //                null);

    //            if (!t.Wait(timeout)) throw new TimeoutException();

    //            return t.Result;
    //        });
    //    }
    //}
}
